<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Edit, Plus, Search} from '@element-plus/icons-vue'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const multipleSelection = ref([])

// 搜索相关
const searchForm = reactive({
  username: ''
})

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const columns = [
  {prop: 'id', label: 'ID', width: '80'},
  {prop: 'avatar', label: '头像', width: '100'},
  {prop: 'username', label: '用户名', width: '120'},
  {prop: 'realName', label: '真实姓名', width: '120'},
  {prop: 'email', label: '邮箱', width: '200'},
  {prop: 'phone', label: '手机号', width: '130'},
  {prop: 'role', label: '角色', width: '100'},
  {prop: 'status', label: '状态', width: '100'},
  {prop: 'createTime', label: '创建时间', width: '180'},
  {prop: 'actions', label: '操作', width: '200', fixed: 'right'}
]


// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://127.0.0.1:8080/file/userinfo', {
      params: {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        username: searchForm.username
      }
    })

    // 假设后端返回格式：{ code: 200, msg: 'success', data: IPage<AdminUser> }
    const result = response.data

    if (result.code === 200) {
      const pageData = result.data  // 即 IPage<AdminUser> 对象

      // 表格要展示的列表数据
      tableData.value = pageData.records || []

      // 总记录数，用于分页组件
      pagination.total = pageData.total || 0
      console.log("返回数据成功！" + result)
    } else {
      ElMessage.error(result.msg || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('获取数据失败，请检查网络或联系管理员')
    console.error('API Error:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getTableData()
}

// 重置搜索
const handleReset = () => {
  searchForm.username = ''
  pagination.currentPage = 1
  getTableData()
}


// 控制新增弹窗的显示与隐藏
const addDialogVisible = ref(false)

const addForm = reactive({
  username: '',
  roleId: '',
  password: '', // 通常需要设置初始密码
})

// 表单校验规则（可选，推荐）
const addFormRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  roleId: [
    {required: true, message: '请选择角色', trigger: 'change'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
  ]
}

// 新增管理员
const handleAdd = () => {
  //打开新增对话框或跳转到新增页面
  addDialogVisible.value = true
}
// 提交新增表单
const submitAddForm = async () => {
  try {

    const response = await axios.post('http://127.0.0.1:8080/file/addUserInfo', addForm)
    const result = response.data
    if (result.code === 200) {
      ElMessage.success('新增管理员成功')
      addDialogVisible.value = false // 关闭弹窗
      // 重置表单（可选）
      Object.assign(addForm, {
        username: '',
        role: '',
        password: '',
      })
      // 刷新表格数据
      getTableData()
    } else {
      ElMessage.error(result.msg || '新增失败')
    }
  } catch (error) {
    console.error('新增管理员失败：', error)
    ElMessage.error('新增管理员失败，请检查网络或联系管理员')
  }
}

// 取消新增，关闭弹窗
const cancelAdd = () => {
  addDialogVisible.value = false
  // 重置表单（可选）
  Object.assign(addForm, {
    username: '',
    role: '',
    password: '',
  })
}

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${multipleSelection.value.length} 条数据吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    // 提取选中行的 ID 数组
    const ids = multipleSelection.value.map(row => row.id)
    // 调用批量删除接口
    const response = await axios.post('http://127.0.0.1:8080/file/deleteAllUserInfo', ids)
    const result = response.data
    if (result.code === 200) {
      ElMessage.success('批量删除成功')
      getTableData() // 刷新表格
    } else {
      ElMessage.error(result.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 单行删除,传入行数据去传ID
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除管理员 "${row.username}" 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    // 实际项目中这里应该调用删除API
    const response = await axios.post(`http://127.0.0.1:8080/file/deleteUserInfo/${row.id}`)

    //得到返回值具体内容
    const result = response.data
    //判断
    if (result.code === 200) {
      ElMessage.success('删除成功')
      getTableData() // 刷新表格
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 编辑
const handleEdit = (row) => {
  ElMessage.info(`编辑管理员 "${row.username}" 功能待开发`)
  // 这里可以打开编辑对话框或跳转到编辑页面
}

// 查看详情
const handleView = (row) => {
  ElMessage.info(`查看管理员 "${row.username}" 详情功能待开发`)
  // 这里可以打开详情对话框或跳转到详情页面
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getTableData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getTableData()
}

// 格式化状态文字
const formatStatusText = (status) => {
  return status === 1 ? '正常' : '禁用'
}

// 格式化状态标签类型
const formatStatusType = (status) => {
  return status === 1 ? 'success' : 'danger'
}

// 格式化角色标签类型（样式用）
const formatRoleType = (roleId) => {
  switch (roleId) {
    case 1:
      return "danger"
    case 2:
      return "warning"
    default:
      return "info"
  }
}


// 格式化角色
const formatRole = (roleId) => {
  switch (roleId) {
    case 1:
      return "超级管理员"
    case 2:
      return "普通管理员"
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getTableData()
})
</script>

<template>
  <div class="admin-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchForm.username"
          class="search-input"
          clearable
          placeholder="请输入用户名"
      >
        <template #prefix>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
      <el-button :icon="Search" type="primary" @click="handleSearch">
        搜索
      </el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 操作按钮栏 -->
    <div class="action-buttons">
      <el-button :icon="Plus" type="primary" @click="handleAdd">
        新增管理员
      </el-button>
      <el-button
          :disabled="multipleSelection.length === 0"
          :icon="Delete"
          type="danger"
          @click="handleBatchDelete"
      >
        批量删除 ({{ multipleSelection.length }})
      </el-button>
    </div>

    <!-- 新增管理员弹窗 -->
    <el-dialog
        v-model="addDialogVisible"
        :before-close="cancelAdd"
        title="新增管理员"
        width="500px"
    >
      <el-form :model="addForm" label-width="80px">
        <el-form-item label="用户名" required>
          <el-input v-model="addForm.username" placeholder="请输入用户名"/>
        </el-form-item>

        <el-form-item label="角色" required>
          <el-select v-model="addForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option label="超级管理员" value="1"/>
            <el-option label="普通管理员" value="2"/>
          </el-select>
        </el-form-item>

        <el-form-item label="密码" required>
          <el-input
              v-model="addForm.password"
              placeholder="请输入密码"
              show-password
              type="password"
          />
        </el-form-item>
      </el-form>

      <template #footer>
    <span class="dialog-footer">
      <el-button @click="cancelAdd">取消</el-button>
      <el-button type="primary" @click="submitAddForm">确定</el-button>
    </span>
      </template>
    </el-dialog>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="50"/>
      <el-table-column align="center" label="序号" type="index" width="60"/>

      <el-table-column align="center" label="头像" prop="avatar" width="80">
        <template #default="{ row }">
          <el-avatar :src="row.avatar" size="small">
            {{ row.username.charAt(0).toUpperCase() }}
          </el-avatar>
        </template>
      </el-table-column>

      <el-table-column label="用户名" prop="username" width="120"/>
      <el-table-column label="真实姓名" prop="realName" width="120"/>
      <el-table-column label="邮箱" prop="email" width="200"/>
      <el-table-column label="手机号" prop="phone" width="130"/>
      <el-table-column align="center" label="角色" prop="roleId" width="100">
        <template #default="{ row }">
          <el-tag :type="formatRoleType(row.roleId)">
            {{ formatRole(row.roleId) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="formatStatusType(row.status)">
            {{ formatStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180"/>

      <el-table-column align="center" fixed="right" label="操作" prop="actions" width="200">
        <template #default="{ row }">
          <el-button
              :icon="Edit"
              link
              size="small"
              type="primary"
              @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
              :icon="View"
              link
              size="small"
              type="info"
              @click="handleView(row)"
          >
            查看
          </el-button>
          <el-button
              link
              size="small"
              type="danger"
              @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped>
.admin-manage {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #fafbfd;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .pagination-container {
    justify-content: center;
  }
}
</style>